package com.quanliang.org.crawlerquanliang.utils;

import java.io.*;
import java.net.URL;

/**
 * 图片工具类
 *
 * @author FYM
 * @data 2022/8/27 4:45
 */
public class ImgUtil {
    //图片URL:https://quan-1259287960.cos.ap-guangzhou.myqcloud.com/1000029/a319dc7572704600be31c7ffa99ccdb0
    static {
        new File("images").mkdir();
    }

    //图片文件夹路径  D:\Code\Java\crawlerquanliang\imgs
    public static final String DIRURL = System.getProperty("user.dir") + "\\images";
    //文件后缀
    public static final String SUFFIX = ".png";


    /**
     * 获取图片文件的绝对路径
     */
    public static String getLocalPath() {
        return DIRURL + "\\" + UUIDUtil.getUUID() + SUFFIX;
    }


    /**
     * 通过链接url下载图片
     */
    private static void downloadImg(String urlImg, String path) {
        try {
            URL url = new URL(urlImg);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 从网络上下载图片
     *
     * @param imgURL 本地绝对路径
     * @return
     */
    public static String downLoadURLImg(String imgURL) {
        String localPath = getLocalPath();
        downloadImg(imgURL, localPath);
        return localPath;
    }
}
